<template>
  <div id="sys-log-index">
    <el-container>
      <el-main>
        <div>
          <el-form :inline="true" size="small" :model="searchForm" class="demo-form-inline" @keyup.enter.native="search()" @submit.native.prevent>
            <el-form-item>
              <el-button type="primary" icon="el-icon-plus" @click="addFile()" v-if="permissions.indexOf('dbFile_sysDbFile_add') > -1">添加</el-button>
            </el-form-item>
            <el-form-item>
              <el-input placeholder="请输入文件名" v-model="searchForm.fileName"/>
            </el-form-item>
            <el-form-item>
              <el-input placeholder="请输入用户名" v-model="searchForm.user_name"/>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="search">查询</el-button>
              <el-button icon="el-icon-search" type="primary" @click="uploadExcel">导入</el-button>
              <el-button icon="el-icon-search" type="primary" @click="exportExcel">导出</el-button>
              <el-button class="margin-left-10" icon="el-icon-delete" @click="reset">清空</el-button>
            </el-form-item>
            <el-form-item v-if="false">
              <el-upload
                  class="upload-demo"
                  action="#"
                  accept=".docx,.pdf,.doc"
                  :limit="1"
                  :http-request="uploadFile"
                  :on-change="handleChange"
                  :on-success="handleBigSuccess"
                  :on-exceed="exceedFile"
                  :before-upload="handleBeforeUpload"
                  :show-file-list="true"
                  :auto-upload="false">
                <el-button type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
            <el-tooltip effect="dark" content="刷新" placement="top-start">
              <el-button size="small" class="float-right" icon="el-icon-refresh" @click="init" circle></el-button>
            </el-tooltip>
          </el-form>
        </div>
        <el-table
            border
            stripe
            :data="fileList"
            ref="sysDictTable"
            size="mini"
            style="width: 100%">
          <el-table-column label="序号" width="50" align="center">
            <template slot-scope="scope">
              <span>{{scope.$index+(pageInfo.current - 1) * pageInfo.pageSize + 1}}</span>
            </template>
          </el-table-column>
          <el-table-column label="备份文件名" prop="fileName" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column label="用户名" prop="userName" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column label="数据库类型" prop="dbType" align="center" :formatter="formatDbType"></el-table-column>
          <el-table-column label="文件类型" prop="fileType" align="center" :formatter="fileDbType" show-overflow-tooltip></el-table-column>
          <el-table-column label="文件路径" prop="filePath" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column label="创建时间" prop="createTime" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" fixed="right" width="80px" align="center">
            <template slot-scope="scope" >
              <el-button type="text" size="small" v-if="permissions.indexOf('dbFile_sysDbFile_return') > -1" icon="el-icon-s-tools" @click="resTore(scope.row)">还原</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end">
          <el-pagination
              :style="{float: 'right', padding: '20px'}"
              class="pageBar"
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pageInfo.current"
              :page-sizes="[5, 10, 20, 30]"
              :page-size="pageInfo.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pageInfo.total">
          </el-pagination>
        </el-row>
      </el-main>
    </el-container>
    <el-dialog
        title="添加" width="580px"
        :visible.sync="dialogFile"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        append-to-body="true">
      <el-container>
        <el-main>
          <el-form
              ref="form"
              :model="form"
              label-width="100px"
              :rules="rules">
            <el-form-item label="备份文件名:"  prop="fileName">
              <el-input v-model="form.fileName"/>
            </el-form-item>
            <el-form-item label="数据库类型:" ref="dbType" prop="dbType">
              <!-- <el-input v-model="form.dbType"/> -->
              <el-radio-group v-model="form.dbType">
                <el-radio disabled :label="1">mysql</el-radio>
                <el-radio disabled :label="2">dm</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="文件类型:" ref="fileType" prop="fileType">
              <!-- <el-input v-model="form.fileType"/> -->
              <el-radio-group v-model="form.fileType">
                <el-radio disabled :label="1">全部</el-radio>
                <el-radio disabled :label="2">数据库</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- <el-form-item prop="file">
              <el-upload
                class="upload-demo"
                action="#"
                accept=".docx,.pdf,.doc"
                :limit="1"
                :http-request="uploadFile"
                :on-change="handleChange"
                :on-success="handleBigSuccess"
                :on-exceed="exceedFile"
                :before-upload="handleBeforeUpload"
                :show-file-list="true"
                :auto-upload="false">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item> -->
          </el-form>
        </el-main>
      </el-container>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-circle-plus-outline" size="small" @click="saveForm" type="primary">确 定</el-button>
        <el-button icon="el-icon-circle-close" size="small" @click="close">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
        customClass="fileIndex"
        :title="importExcel.title"
        :visible.sync="importExcel.visible"
        width="600px"
        append-to-body="true"
        :close-on-click-modal="false"
        @close="cancelImportExcelDialog()">
      <el-container>
        <el-main>
          <el-upload drag
              accept=".xlsx"
              class="upload-demo"
              action="#"
              :limit="1"
              :on-change="excelHandleChange"
              :on-remove="excelHandleRemove"
              :multiple="false"
              :before-upload="excelBeforeUpload"
              :show-file-list="true"
              :auto-upload="true">
            <i class="el-icon-upload"></i>
            <div class="el-upload_text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload_tip" slot="tip">只能上传xlsx文件，且不超过10M</div>
          </el-upload>
        </el-main>
      </el-container>
      <div slot="footer" class="dialog-footer" v-show="!isFileLook">
        <el-button @click="importExcelSubmit" type="primary">确 定</el-button>
        <el-button @click="cancelImportExcelDialog">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import sysDbFileApi from "./api/sysDbFile.service";
import { Loading } from "element-ui";
const loadingOption = {
  fullscreen: true,
  lock: true,
  text: "Loading",
  spinner: "el-icon-loading",
  background: "rgba(0, 0, 0, 0.7)"
};
let loadingInstance;

export default {
  components: {},
  data() {
    return {
      importExcel:{
        file: "",
        title: '',
        visible: false,
      },
      rules: {
        fileName: [
          {
            required: true,
            message: "备份文件名不能为空！",
            trigger: "blur"
          }
        ],
        dbType: [
          {
            required: true,
            message: "数据库类型不能为空！",
            trigger: "blur"
          }
        ],
        fileType: [
          {
            required: true,
            message: "文件类型不能为空！",
            trigger: "blur"
          }
        ],
        // file: [
        //   {
        //     required: true,
        //     message: "请上传文件！",
        //     trigger: "change"
        //   }
        // ]
      },
      permissions: JSON.parse(sessionStorage.getItem('permissions')),
      dialogFile: false,
      fileList: [],
      searchForm: {
        fileName: '',
        user_name: ''
      },
      form: {
        fileName: '',
        dbType: 1,
        fileType: 2
      },
      pageInfo: {
        current: 1,
        pageSize: 10,
        total: 0
      }
    };
  },
  created() {
    this.init()
  },
  methods: {
    // 加载标示
    LoadingOpen() {
      const loading = Loading.service({
        fullscreen: true,
        lock: true,
        text: "正在努力还原中，请稍后！",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      })
      return loading
    },
    // 加载标示关闭
    LoadingClose(loading) {
      loading.close();
    },
    // 还原
    resTore (row) {
      this.$confirm("本操作不可逆，是否继续还原？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.LoadingOpen();
          let params = {
            dbType: row.dbType,
            fileName: row.fileName,
            filePath: row.filePath,
            fileType: row.fileType
          };
          sysDbFileApi.restoreSysDbFile(params).then(res => {
            if (res.code == 10200) {
              this.LoadingClose(this.LoadingOpen());
              this.$message.success("还原成功！");
              this.init();
              this.close();
            } else {
              this.LoadingClose(this.LoadingOpen());
              this.$message.error(res.msg);
            }
          })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消！"
          });
        });

    },
    search(){
      this.init()
    },
    reset(){
      this.searchForm.fileName = '';
      this.searchForm.user_name = '';
      this.init()
    },
    formatDbType: function (row) {
      return row.dbType === 1 ? 'MySql' : row.dbType === 2 ? '达梦数据库' : '未知'
    },
    fileDbType: function (row) {
      return row.fileType === 1 ? '全部' : row.fileType === 2 ? '数据库' : '未知'
    },
    // 保存
    saveForm () {
      let _this = this;
      this.$refs["form"].validate(valid => {
        if (valid) {
          sysDbFileApi.saveSysDbFile(this.form).then(res => {
            if (res.code == 10200) {
              this.$message.success("添加成功！");
              _this.close();
              _this.init();
            } else {
              _this.$message.error(res.msg);
            }
          });
        }
      });
    },
    // 取消
    close () {
      let obj = {
        fileName: '',
        dbType: 1,
        fileType: 2
      };
      this.form = obj;
      this.$nextTick(() => {
        this.$refs["form"].resetFields();
      });
      this.dialogFile = false;
    },
    // 添加
    addFile () {
      this.dialogFile = true;
    },
    // 初始化数据
    init () {
      let _this = this;
      let params = Object.assign({
        current: this.pageInfo.current,
        size: this.pageInfo.pageSize,
        fileName: this.searchForm.fileName,
        userName: this.searchForm.user_name
      });
      sysDbFileApi.getSysDbFilePage(params).then(res => {
        _this.fileList = res.data.records;
        _this.pageInfo.total = res.data.total;
      });
    },
    // 上传
    uploadFile () {

    },
    handleChange (file, fileList) {
      this.form.file = file.name;
    },

    handleRemove(file) {
    },

    handleBigSuccess (res, file) {

    },

    handleBeforeUpload (file) {

    },

    /**
     * 上传之前
     */
    excelBeforeUpload (file) {
      debugger
      console.log(file.type)
      console.log(file.size)
    },
    exceedFile (files, fileList) {
      this.$message.warning({
        title: '警告',
        message: `只能上传一个文件，当前一共选择了一个文件`
      })
    },
    // 改变页码
    handleSizeChange(val) {
      this.pageInfo.pageSize = val;
      this.init();
    },

    handleCurrentChange(val) {
      this.pageInfo.current = val;
      this.init();
    },

    excelHandleChange (file) {
      this.importExcel.file = file.raw;
    },

    excelHandleRemove(file) {
      this.importExcel.file = "";
    },

    /**
     * 导出excel
     */
    exportExcel() {
      let _this = this;
      let params = Object.assign({
        current: this.pageInfo.current,
        size: this.pageInfo.pageSize,
        fileName: this.searchForm.fileName,
        userName: this.searchForm.user_name
      });
      sysDbFileApi.exportExcel(params).then(res => {});
    },

    /**
     * 关闭导入弹窗
     */
    cancelImportExcelDialog(){
      this.importExcel.visible = false;
    },


    /**
     * 导入excel
     * */
    uploadExcel(){
      this.importExcel.visible = true;
      this.importExcel.title = '导入excel';
    },

    /**
     * 导入excel
     */
    importExcelSubmit() {
      let formData = new FormData()
      if (this.importExcel.file) {
        formData.append('file', this.importExcel.file)
        sysDbFileApi.importExcel(formData).then(res => {
          debugger
          if (res.code === 10200) {
            this.$message({
              type: "success",
              message: "导入成功！"
            })
            this.cancelImportExcelDialog();
            this.init();
          }
        })
      } else {
        this.$message({
          type: "error",
          message: "请选择文件！"
        })
      }
    },
  }
};
</script>

<style scoped>
  .float-right {
    float: right;
  }
</style>
